#include <zenoui/widgets/GraphicsItemWidget.hpp>
#include <zenoui/widgets/GraphicsViewWidget.hpp>
#include <zenoui/check_gl.hpp>
#include <zenox/minilog.hpp>

namespace zenoui {

void GraphicsItemWidget::handle(MouseClickEvent *event) {
    if (m_draggable && event->button() == MouseLeftButton) {
        event->accept(this);
    }
    if (m_selectable && event->button() == MouseLeftButton) {
        auto view = static_cast<GraphicsViewWidget *>(parent());
        bool ctrl = event->mods() & ModifierCtrl;
        if (!ctrl) {
            for (auto const &item: view->m_selected_items)
                if (item) [[likely]] item->m_selected = false;
            view->m_selected_items.clear();
        }
        if (auto [it, succ] = view->m_selected_items.insert(zenox::weak_from(this)); !succ) {
            if (auto node = *it) [[likely]]
                node->m_selected = false;
            view->m_selected_items.erase(it);
            ZENO_ASSERT(view->m_selected_items.insert(zenox::weak_from(this)).second);
        }
        m_selected = true;
        event->accept(this);
    }
}

ZENO_HOT_FN void GraphicsItemWidget::handle(MouseMoveEvent *event) {
    if (m_draggable && event->button() == MouseLeftButton) {
        zenox::log_trace("GraphicsWidget handling mouse move mouse={}, mypos={}, delta={}",
                         event->pos(), position(), event->delta_pos());
        set_position(position() + event->delta_pos());
        event->accept(this);
    }
}

void GraphicsItemWidget::handle(MouseReleaseEvent *event) {
    if (m_draggable && event->button() == MouseLeftButton) {
        event->accept(this);
    }
}

ZENO_HOT_FN void GraphicsItemWidget::set_position(glm::vec2 const &pos) {
    modify_shape([&] (Shape &sp) {
        sp.position = pos;
    });
    sig_updatePosition();
}

GraphicsItemWidget::GraphicsItemWidget() {
    /* auto sp = shape(); */
    /* sp.margins = {}; */
    /* sp.paddings = {}; */
    /* set_shape(sp); */
}

GraphicsItemWidget::~GraphicsItemWidget() = default;

}
